package com.web;

import com.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UserServlet  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //每次调用doGet都会加载配置文件spring容器也会被创建多次，
        // 所以加入监听器(ServletContextListener)在启动web项目时创建并把容器放入ServletXContext域中(web全局)
        //需要时可以在任意位置直接从ServletContext中获取
        //ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
        //获取ServletContext域对象
        ServletContext servletContext = req.getServletContext();
        /*//通过键来获取容器
        ApplicationContext app = (ApplicationContext)servletContext.getAttribute("app");*/
        //通过工具类WebApplicationContextUtils(手写)直接获取容器
        //ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        //通过spring自带的WebApplicationContextUtils获取容器
        ApplicationContext app = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        //通过容器获取UserService bean
        UserService userService = app.getBean(UserService.class);
        userService.save();

    }
}
